package com.kfm.hotel.interceptor;

import com.anji.captcha.util.AESUtil;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.service.SysUserService;
import com.kfm.hotel.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@RequestBody:将前端数据传递给后台
@Component
public class RememberMeInterceptor implements HandlerInterceptor {
    @Autowired
    private SysUserService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //已经登录过的用户直接重定向到首页
          Object user= request.getSession().getAttribute(Constant.LOGIN_USER);
            //判断session中是否有用户信息
           if(user!=null) {
               response.sendRedirect("/index");
                return false;
           }
        //1.获取cookies
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies) {
            //2.判断是否有RenemberMe的Cookie
            if(Constant.REMEMBER_ME_COOKIE_NAME.equals(cookie.getName())){
                //3.进行分割，解密
                String[] split=cookie.getValue().split("--");
                String username = AESUtil.aesDecrypt(split[0], Constant.REMEMBER_ME_AES_KEY);
                String password = AESUtil.aesDecrypt(split[1],Constant.REMEMBER_ME_AES_KEY);
                SysUser login01 = service.login(username, password);
                //4.判断登录是否成功
                if(login01!=null){
                    //请求重定向
                    request.getSession().setAttribute(Constant.LOGIN_USER,login01);
                    response.sendRedirect("/index");
                    return false;
                }
            }

        }
        return true;
    }
}
